<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="myWait">待我处理</el-menu-item>
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="needSettle">后结算</el-menu-item>
<!--      <el-menu-item index="closed">交易关闭</el-menu-item>-->
      <el-menu-item index="all" v-if="isCanPurchaseContractByAll">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
        <el-form-item label="采购订单号：">
          <el-input v-model="listQuery.orderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="采购日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.createDate"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商：">
          <el-select
            clearable
            v-model="listQuery.supplierId"
            filterable
            reserve-keyword
            placeholder="请输入关键词"
            style="width: 220px;">
            <el-option
              v-for="item in options2"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同公司：">
          <el-input v-model="listQuery.fromCompany" style="width: 220px;" clearable></el-input>
        </el-form-item>

        <el-form-item label="品名：">
          <el-input v-model="listQuery.goodsName" clearable></el-input>
        </el-form-item>

        <el-form-item label="牌号：">
          <el-autocomplete
            clearable
            style="width:300px;"
            class="inline-input"
            v-model="listQuery.goodsSn"
            :fetch-suggestions="querySearchGoodsSn"
            placeholder="请输入内容"
            @select="handleSelectGoodsSn"
          >
            <template slot-scope="{ item }">
              <div>{{ item.goodsSn }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>


        <el-form-item label="业务员：" >
          <el-select v-model="listQuery.purchaseUserId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同状态："  v-if="listQuery.tab == 'my' ||listQuery.tab == 'all'">
          <el-select v-model="listQuery.orderState" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in stateList"
                    :key="item.val"
                    :label="item.label"
                    :value="item.val">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交货日期：" >
            <el-date-picker
                    :default-time="['00:00:00', '23:59:59']"
                    v-model="listQuery.sendDate"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="付款状态："  >
          <el-select v-model="listQuery.payState" filterable placeholder="请选择" multiple >
            <el-option :key="0" label="未付款" :value="0"></el-option>
            <el-option :key="1" label="部分付款" :value="1"></el-option>
            <el-option :key="2" label="已付款" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入库状态："  >
          <el-select v-model="listQuery.goodsInState" placeholder="请选择" clearable multiple>
            <el-option :key="0" label="未入库" :value="0"></el-option>
            <el-option :key="1" label="部分入库" :value="1"></el-option>
            <el-option :key="2" label="已入库" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="安排提货状态："  >
          <el-select v-model="listQuery.goodsTakeState" filterable placeholder="请选择" clearable>
            <el-option :key="0" label="未安排提货" :value="0"></el-option>
            <el-option :key="1" label="已部分安排提货" :value="1"></el-option>
            <el-option :key="2" label="已安排全部提货" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="采购员：" >
          <el-select v-model="listQuery.buyerUserId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="投委订单：" >
          <el-select v-model="listQuery.isEntrust"  placeholder="请选择" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算状态：" >
          <el-select v-model="listQuery.orderSettleState"  placeholder="请选择" clearable>
            <el-option label="未结算" value="10"></el-option>
            <el-option label="部分结算" value="20"></el-option>
            <el-option label="已结算" value="30"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
            type="primary"
            v-if="listQuery.tab != 'all'"
            @click="addOrder">
            新增采购订单
          </el-button>
          <el-button
                  v-if="listQuery.tab == 'all' && AllPurchaseContractExport"
                  @click="downloadExcel">
            导出
          </el-button>
          <el-button
                  :loading="btnLoading2"
                  v-if="listQuery.tab == 'all' && downLoadPurchaseContract"
                  @click="handleBatchDownload">
            批量下载合同附件
          </el-button>
        </el-form-item>
      </el-form>
    </div>

      <!--数据列表-->
    <div style="font-size:14px;line-height: 30px;padding:10px 0 ">
      合同金额：<span style="font-weight: bold">{{statisticsAmount}}</span>
      <span style="padding-left:20px;">商品数量：</span><span style="font-weight: bold">{{statisticsGoodsNum}}</span>
      <span style="padding-left:20px;">采购实际数量：</span><span style="font-weight: bold">{{authNum}}</span>
      <span style="padding-left:20px;">不执行数量：</span><span style="font-weight: bold">{{closeNum}}</span>
      <span style="padding-left:20px;">不执行金额：</span><span style="font-weight: bold">{{closeAmount}}</span>
    </div>
    <div class="table-container">
        <el-table
          :header-cell-style="{'text-align':'center'}"
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column
                  label="采购日期"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.createTime}}
            </template>
          </el-table-column>
          <el-table-column  label="采购订单号" width="180" align="center">
            <template slot-scope="scope">
              {{scope.row.orderSn}}
              <img src="../../assets/images/zhuofei2.png" v-if="scope.row.orderState == 10" style="vertical-align: middle;"/>
              <img src="../../assets/images/bian.png" v-if="scope.row.isChange==1" style="vertical-align: middle;"/>
              <span v-if="scope.row.isEntrust == 1" style="display: inline-block;width:22px;line-height: 18px;background: green;color:#fff;font-size:12px;border-radius: 4px">投</span>
            </template>
          </el-table-column>
          <el-table-column
                  label="供应商名称"
                  width="200">
            <template slot-scope="scope">
              {{scope.row.supplierName}}
            </template>
          </el-table-column>
          <el-table-column
                  label="合同公司"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.fromCompany}}
            </template>
          </el-table-column>
          <el-table-column
                  label="业务员"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.userName}}
            </template>
          </el-table-column>
          <el-table-column
                  label="采购员"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.buyerUserName}}
            </template>
          </el-table-column>
          <el-table-column
            label="结算状态"
            width="100"
            align="center">
            <template slot-scope="scope">
                {{scope.row.orderSettleState | fifSettleState}}
            </template>
          </el-table-column>
<!--          <el-table-column-->
<!--                  label="交货日期"-->
<!--                  width="100"-->
<!--                  align="center">-->
<!--            <template slot-scope="scope">-->
<!--              {{scope.row.sendDate}}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column
                  label="合同数量"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.goodsAllNum}}
            </template>
          </el-table-column>
          <el-table-column
                  label="合同金额"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.orderAmount}}
            </template>
          </el-table-column>
          <el-table-column
                  label="已付款金额"
                  width="100"
                  align="center">
            <template slot-scope="scope">
                 {{scope.row.hasPaidAmount}}
            </template>
          </el-table-column>
          <el-table-column
                  label="未付款金额"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.unPaidAmount}}
            </template>
          </el-table-column>
          <el-table-column
                  label="申请中金额"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.applyAmount}}
            </template>
          </el-table-column>
<!--          <el-table-column-->
<!--                  align="center"-->
<!--                  label="发货方式"-->
<!--                  width="150">-->
<!--            <template slot-scope="scope">-->
<!--              {{scope.row.deliveryType}}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column
                  align="center"
                  label="入库状态"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsInState }}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="已入库数量"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsInNum}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="未入库数量"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsUnInNum}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="已入库金额 "
                  width="100">
            <template slot-scope="scope">
                  {{scope.row.goodsInAmount}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="提货状态"
                  width="100">
            <template slot-scope="scope">
                {{scope.row.goodsTakeState}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="已提货数量"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsTakeNum}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="未提货数量 "
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsUnTakeNum}}
            </template>
          </el-table-column>
<!--          <el-table-column-->
<!--                  align="center"-->
<!--                  label="结算方式"-->
<!--                  width="150">-->
<!--            <template slot-scope="scope">-->
<!--              {{scope.row.remark}}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column
                  align="center"
                  label="付款状态"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.payState | fiferPayState}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="付款时间"
                  width="150">
            <template slot-scope="scope">
              {{scope.row.payTime}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="发货方式"
                  width="150">
            <template slot-scope="scope">
              {{scope.row.sendType}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="运费方式"
                  width="150">
            <template slot-scope="scope">
              {{scope.row.freightType}}
            </template>
          </el-table-column>

          <el-table-column
                  fixed="right"
                  align="center"
                  label="状态"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.orderState | fifterState}}
            </template>
          </el-table-column>
          <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="150">
            <template slot-scope="scope">
                <el-button type="text" @click="toInfo(scope.row)">查看</el-button>
                <el-button type="text" @click="showDialog3(scope.row)" v-if="scope.row.unPaidAmount > 0  && scope.row.orderState == 40">申请支付</el-button>
<!--                <el-button type="text" @click="toAddPickUp(scope.row)" v-if="scope.row.goodsUnTakeNum > 0 && (listQuery.tab == 'my' || listQuery.tab == 'all') && scope.row.orderState == 40">生成提货单</el-button>-->
                <el-button type="text" @click="setIsEntrust(scope.row)" v-if="changePurchaseOrderIsEntrust && scope.row.isEntrust == 2">设为投委会订单</el-button>
                <el-button type="text" @click="setIsEntrust(scope.row)" v-if="changePurchaseOrderIsEntrust && scope.row.isEntrust == 1">取消投委会订单</el-button>
                <el-button type="text" @click="showNewHQ(scope.row)" v-if="scope.row.orderState == 40">生成货权</el-button>
                <el-button type="text" @click="showAfterSettlement(scope.row)" v-if="listQuery.tab == 'needSettle' && scope.row.orderSettleState != 30 && (scope.row.orderState == 40 || scope.row.orderState == 50)">申请结算</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

      <!--申请支付-->
      <el-dialog
              :close-on-click-modal="false"
              :beforeClose="handleClose3"
              title="申请付款"
              :visible.sync="dialogVisible3"
              width="400px">
          <el-form :model="appleForm" size="mini" label-width="140px"  ref="appleForm" :rules="rules3">
               <el-form-item label="供应商：" >{{appleForm.supplierName}}</el-form-item>
               <el-form-item label="合同公司：" >{{appleForm.fromCompany}}</el-form-item>
              <el-form-item label="合同金额：" >{{appleForm.orderAmount}}</el-form-item>
              <el-form-item label="已支付金额：" >{{appleForm.hasPaidAmount}}</el-form-item>
              <el-form-item label="未付款金额：">{{appleForm.unPaidAmount}}</el-form-item>
              <el-form-item label="可申请金额：">{{appleForm.canApplyAmount}}</el-form-item>
              <el-form-item label="目前预付款额度："><span style="color:Red">{{appleForm.currentPrePayAmount}}</span></el-form-item>
              <el-form-item label="商品备注：">
                 {{appleForm.goodsRemark}}
              </el-form-item>
              <el-form-item label="付款方式：" prop="applyPaymentCode">
                <el-select v-model="appleForm.applyPaymentCode" class="input-width" style="width:195px" placeholder="请选择">
                  <el-option value="cash" label="现汇" key="cash" ></el-option>
                  <el-option value="chengdui" label="承兑" key="chengdui" ></el-option>
                  <el-option value="cashBalance" :label="'现金余额'+'('+appleForm.CashBalance+')'" key="cashBalance" ></el-option>
                  <el-option value="chengduiBalance" :label="'承兑余额'+'('+appleForm.ChengduiBalance+')'" key="chengduiBalance" ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="申请付款金额：" prop="applyPayAmount">
              <el-input v-model="appleForm.applyPayAmount"></el-input>
            </el-form-item>
            <el-form-item label="付款紧急程度：" prop="urgencyType">
              <el-select v-model="appleForm.urgencyType" class="input-width" style="width:195px" placeholder="请选择">
                <el-option value="紧急" label="紧急" key="紧急" ></el-option>
                <el-option value="普通" label="普通" key="普通" ></el-option>
              </el-select>
            </el-form-item>
              <el-form-item label="付款时间：" prop="applyPayTime">
                  <el-date-picker
                          v-model="appleForm.applyPayTime"
                          value-format="yyyy-MM-dd HH:mm"
                          type="datetime"
                          placeholder="选择日期时间">
                  </el-date-picker>
              </el-form-item>
              <el-form-item label="付款备注：">
                  <el-input v-model="appleForm.applyPayRemark" :autosize="{ minRows: 2, maxRows: 6}" type="textarea"></el-input>
              </el-form-item>
          </el-form>
         <div style="color:red;padding:0 16px;font-size:12px">注：选择承兑支付时，请确认已有承兑票据</div>
          <span slot="footer" class="dialog-footer">
              <el-button @click="handleClose3">取 消</el-button>
              <el-button type="primary" @click="handleConfirm3" :loading="btnLoading3">确 定</el-button>
          </span>
      </el-dialog>

      <!--生成货权-->
      <el-dialog
        :close-on-click-modal="false"
        :beforeClose="handleClose4"
        title="生成货权"
        :visible.sync="dialogVisible4"
        width="400px">
        <el-form :model="setForm" size="mini" label-width="80px"  ref="setForm">
             <div style="border-bottom: 1px solid #eee" v-for="item in setInfo.ordGoodsList">
                 <el-form-item label="牌号：">{{item.goodsSn}}</el-form-item>
                 <el-form-item label="数量：">{{item.goodsNum}}</el-form-item>
                 <el-form-item label="价格：">{{item.goodsPrice}}</el-form-item>
             </div>
            <el-form-item label-width="0px" style="margin-top: 10px;margin-bottom: 0">
                <el-checkbox v-model="setForm.isAutoMove">开启自动货权转移</el-checkbox>
            </el-form-item>
            <el-form-item label-width="0px">
              <el-checkbox v-model="setForm.isLimitOrder">开启限制下单</el-checkbox>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose4">取 消</el-button>
            <el-button type="primary" @click="handleConfirm4" :loading="btnLoading4">确 定</el-button>
        </span>
      </el-dialog>


      <!--合同结算-->
      <el-dialog
        :close-on-click-modal="false"
        :beforeClose="handleClose5"
        title="合同结算"
        :visible.sync="dialogVisible5"
        width="800px">
        <el-form :model="settlementForm" size="mini" label-width="80px"  ref="settlementForm">
          <el-table
            ref="orderItemTable"
            :data="orderInfo.ordGoodsList"
            style="width: 100%;margin-top: 20px" border>
            <el-table-column label="商品名称" min-width="160" align="center">
              <template slot-scope="scope">
                {{scope.row.goodsName}}
              </template>
            </el-table-column>
            <el-table-column label="商品牌号" align="center" min-width="160">
              <template slot-scope="scope">
                {{scope.row.goodsSn}}
              </template>
            </el-table-column>
            <el-table-column label="数量"   min-width="100"  align="center">
              <template slot-scope="scope">
                {{scope.row.goodsNum}}
              </template>
            </el-table-column>
            <el-table-column label="原合同单价" min-width="150" align="center">
              <template slot-scope="scope">
                {{scope.row.oldPrice}}
              </template>
            </el-table-column>
            <el-table-column label="结算申请状态" min-width="150" align="center">
              <template slot-scope="scope">
                {{scope.row.pogSettleState | fifpogSettleState}}
              </template>
            </el-table-column>
            <el-table-column label="结算方式"  min-width="150" align="center" fixed="right">
              <template slot-scope="scope">
                 {{scope.row.goodsSettleType}}
              </template>
            </el-table-column>
            <el-table-column label="申请结算价"  min-width="150" align="center" fixed="right">
              <template slot-scope="scope">
                <el-input  v-model="scope.row.settlePrice" size="small" :disabled="scope.row.pogSettleState != 10"></el-input>
              </template>
            </el-table-column>

          </el-table>
        </el-form>
        <span slot="footer" class="dialog-footer">
              <el-button @click="handleClose5">取 消</el-button>
              <el-button type="primary" @click="handleConfirm5" :loading="btnLoading5">确 定</el-button>
          </span>
      </el-dialog>

  </div>
</template>
<script>
  import {changeOrderIsEntrust,getCustomerOption,getOrderUsersList,purchaseOrderList,supplierList,purchaseAddApplyPay,supplierBalanceInfo,orderGoodsList} from '@/api/partner'
  import {goodsList,generateOwnership,purchaseOrderDetail,purchaseOrderGoodsDetail,purchaseSettlePriceApply} from '@/api/company'
  import {formatDate} from '@/utils/date';
  import store from '@/store'
  import { mapGetters } from 'vuex'
  import {validateCommission4} from '@/utils/validate';
  import JSZip from 'jszip'
  import axios from 'axios'
  import FileSaver from 'file-saver'
  const defaultListQuery={
    pageNum: 1,
    pageSize: 10,
    supplierId: '',
    orderSn:'',
    goodsKingId:'',
    purchaseUserId:'',
    fromCompany:'',
    createDate:null,
    sendDate:null,
    tab:'myWait',
    orderState:null,
    goodsName : "", //品名
    payState:[],
    goodsInState:[],
    goodsTakeState:null,
    buyerUserId:'',
    isEntrust:'',
    orderSettleState:'',
    goodsSn:''
  };
  const defaultAppleForm={
    "orderId"     : '',    //采购单ID
    "applyPaymentCode" : "",  //支付方式
    "applyPayTime"   : "",    //支付时间
    "applyPayAmount" : '',  //支付金额
    "applyPayRemark" : "" , //备注
    orderAmount:'',
    unPaidAmount:'',
    hasPaidAmount:'',
    canApplyAmount:'',
    contractUrl:'',
    fromCompany:'',
    supplierName:'',
    CashBalance:'',
    ChengduiBalance:'',
    goodsRemark:'',
    urgencyType:'',
    currentPrePayAmount:'',//目前预付款额度
  };
  const defaultsetForm={
    "orderId"     : '',    //采购单ID
    isAutoMove : false, //下单是否自动转移货权(1是，0否)
    isLimitOrder : false //没货权是否不能下单(1是，0否)
  };

  const defaultsettlementForm={
    "orderId"     : '',    //采购单ID
    isAutoMove : false, //下单是否自动转移货权(1是，0否)
    isLimitOrder : false //没货权是否不能下单(1是，0否)
  };
  export default {
    name: "index",
    data(){
      const isvalidateApplyPayAmount = (rule, value, callback) => {
        if (!validateCommission4(parseFloat(value))) {
          callback(new Error('非负整数或小数'))
        }else if(this.appleForm.applyPaymentCode == 'cash' && value > this.appleForm.canApplyAmount){
          callback(new Error('超过可申请金额'))
        }else if(this.appleForm.applyPaymentCode == 'chengdui' &&  this.appleForm.canApplyAmount <= 0){
          callback(new Error('可申请金额小于等于0，不可以再次申请'))
        }else if(this.appleForm.applyPaymentCode == 'cashBalance' && value > this.appleForm.canApplyAmount){
          callback(new Error('超过可申请金额'))
        }else if(this.appleForm.applyPaymentCode == 'cashBalance' && value > this.appleForm.CashBalance){
          callback(new Error('超过现金余额'))
        }else if(this.appleForm.applyPaymentCode == 'chengduiBalance' && value > this.appleForm.canApplyAmount){
          callback(new Error('超过可申请金额'))
        }else if(this.appleForm.applyPaymentCode == 'chengduiBalance' && value > this.appleForm.ChengduiBalance){
          callback(new Error('超过承兑余额'))
        }else {
          callback()
        }
      };

      return {
        listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
        tableData: [],
        count: 0,
        listLoading: false,
        userOptionList:[],
        roles:store.getters.roles ? store.getters.roles : [],
        loading:false,
        options:[],
        loading2:false,
        options2:[],
        goodsList:[],
        stateList:[
          {label:'待采购员审核',val:0},
          {label:'作废',val:10},
          {label:'待产品负责人审核',val:20},
          {label:'待采购部门负责人确认',val:23},
          {label:'待总经理审核',val:25},
          {label:'流程结束',val:40},
          {label:'交易关闭',val:50},
        ],
        statisticsAmount:'',
        statisticsGoodsNum:'',
        dialogVisible3:false,
        rules3:{
          applyPaymentCode:[{required: true, trigger: 'change' ,message: '请选择支付方式',}],
          applyPayTime:[{required: true, trigger: 'change' ,message: '请选择支付时间',}],
          applyPayAmount:[{required: true, trigger: 'blur' ,validator:isvalidateApplyPayAmount,}],
          urgencyType:[{required: true, trigger: 'change' ,message: '请选择紧急程度',}],
          },
        appleForm:JSON.parse(JSON.stringify(defaultAppleForm)),
        btnLoading3:false,
        btnLoading2:false,
        authNum:'',
        closeNum:'',
        closeAmount:'',

        dialogVisible4:false,
        setForm:JSON.parse(JSON.stringify(defaultsetForm)),
        btnLoading4:false,
        setInfo:{ordGoodsList:[]},


        dialogVisible5:false,
        settlementForm:JSON.parse(JSON.stringify(defaultsettlementForm)),
        btnLoading5:false,
        orderInfo:{}
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId',
        'isMange',
      ]),
      isCanPurchaseContractByAll(){
        if(this.roles.indexOf("AllPurchaseContract") != -1){
          return true
        }else{
          return false
        }
      },
      AllPurchaseContractExport(){
        if(this.roles.indexOf("AllPurchaseContractExport") != -1){
          return true
        }else{
          return false
        }
      },
      downLoadPurchaseContract(){
        if(this.roles.indexOf("downLoadPurchaseContract") != -1){
          return true
        }else{
          return false
        }
      },

      changePurchaseOrderIsEntrust (){
        if(this.roles.indexOf("changePurchaseOrderIsEntrust") != -1){
          return true
        }else{
          return false
        }
      },
    },
    created() {
      if(this.$route.query.dataTab){
        this.listQuery.tab = this.$route.query.dataTab
      }
      if(this.$route.query.dataGoodsClass){
        this.listQuery.goodsName = this.$route.query.dataGoodsClass
      }
      if(this.$route.query.dataKingGoodsId){
        this.listQuery.kingGoodsId = Number(this.$route.query.dataKingGoodsId)
      }
      if(this.$route.query.dataGoodsInState){
        let numArray = this.$route.query.dataGoodsInState.map(str => Number(str));
        this.listQuery.goodsInState = numArray
      }
      if(this.$route.query.dataPayState){
        this.listQuery.payState = [Number(this.$route.query.dataPayState)]
      }
      if(this.$route.query.tab){
        this.listQuery.tab = this.$route.query.tab
      }
      if(this.$route.query.payState){
        let stringArray = this.$route.query.payState.split(',')
        let numberArray = stringArray.map(Number);
        this.listQuery.payState = numberArray
      }
      if(this.$route.query.orderState){
        this.listQuery.orderState = Number(this.$route.query.orderState)
      }
      if(this.$route.query.createDate){
        this.listQuery.createDate = this.$route.query.createDate.split(',')
      }
      this.getList();
      this.getUserOptionList();
      this.getSupplierList();
      this.getGoodsList()
    },
    filters: {
      formatCreateTime(time) {
        if(time){
          let date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
        }else{
          return '--'
        }
      },
      fiferPayState(val){
        if(val == 0){
          return '未付款'
        }else if(val == 1){
          return '部分付款'
        }else if(val == 2){
          return '已付款'
        }
      },
      fifterState(val){
        if(val == 0){
          return '待采购员审核'
        }else if(val == 10){
          return '作废'
        }else if(val == 20){
          return '待产品负责人审核'
        }else if(val == 23){
          return '待采购部门负责人确认'
        }else if(val == 25){
          return '待总经理审核'
        }else if(val == 30){
          return '待财务负责人审核'
        }else if(val == 40){
          return '流程结束'
        }else if(val == 50){
          return '交易关闭'
        }
      },
      fifTakeState(val){
        if(val == 0){
          return '未安排提货'
        }else if(val == 1){
          return '已部分安排提货'
        }else if(val == 2){
          return '已安排全部提货'
        }
      },
      fifpogSettleState(val){
        if(val == 10){
          return '未申请结算'
        }else if(val == 20){
          return '结算审批中'
        }else if(val == 30){
          return '审批通过'
        }
      },
      fifSettleState(val){
        if(val == 0){
          return '未申请开票后结算'
        }else if(val == 10){
          return '未结算'
        }else if(val == 20){
          return '部分结算'
        }else if(val == 30){
          return '已结算'
        }
      },
    },
    methods:{
      handleSelectGoodsSn(item){
        this.listQuery.goodsSn = item.goodsSn
      },
      getGoodsList(){
        orderGoodsList().then((res)=>{
          this.goodsList = res.list
        })
      },
      querySearchGoodsSn(queryString, cb){
        let restaurants = this.goodsList;
        let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.goodsSn.indexOf(queryString)!=-1);
        };
      },
      handleClose5(){
        this.dialogVisible5 = false
      },
      handleConfirm5(){
        let isnull = 0
        let ordGoodsList = []
        this.orderInfo.ordGoodsList.forEach((el)=>{
          ordGoodsList.push({pogId:el.pogId,settlePrice:el.settlePrice})
          if(el['settlePrice'] >0){
            isnull = 1
          }
        })
        if(isnull == 0){
          this.$message.error('至少需填写一条申请结算价！')
          return false
        }
        this.btnLoading5 = true;
        let data = {}
        data.orderId = this.orderInfo.orderId
        data.ordGoodsList = ordGoodsList
        purchaseSettlePriceApply(data).then(()=>{
          this.$message.success('提交成功')
          this.getList()
          this.btnLoading5 = false;
          this.handleClose5()
        }).catch(()=>{
          this.btnLoading5 = false;
        })
      },
      showAfterSettlement(item){
        this.dialogVisible5 = true
        purchaseOrderGoodsDetail({orderId:item.orderId}).then((res)=>{
            this.orderInfo = res
        })
      },
      addOrder(){
        this.$router.push({name:'addPurchaseOrder'})
      },
      showNewHQ(item){
          this.setForm = JSON.parse(JSON.stringify(defaultsetForm))
          this.setForm.orderId = item.orderId
          this.setInfo.ordGoodsList = []
          purchaseOrderDetail({orderId:item.orderId}).then((res)=>{
             this.setInfo = res
             this.dialogVisible4 = true
          })
      },
      handleClose4(){
        this.dialogVisible4 = false
      },
      handleConfirm4(){
        this.btnLoading4 = true;
        let data = JSON.parse(JSON.stringify(this.setForm))
        data.isAutoMove = data.isAutoMove ? 1 : 0;
        data.isLimitOrder = data.isLimitOrder ? 1 : 0
        generateOwnership(data).then(()=>{
          this.btnLoading4 = false;
          this.getList()
          this.dialogVisible4 = false
        }).catch(()=>{
          this.btnLoading4 = false;
        })

      },
      setIsEntrust(item){
        let msg = item.isEntrust == 1 ? '确认将此订单取消投委会订单设置?' : '确认将此订单设为投委会订单?'
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          changeOrderIsEntrust({orderId:item.orderId,isEntrust:item.isEntrust == 1 ? 2 : 1}).then(()=>{
            this.getList();
            this.$message({
              type: 'success',
              message: '设置成功!'
            });
          });
        }).catch(() => {

        });
      },
      //批量下载
      handleBatchDownload(){
        this.btnLoading2 = true;
        let pamas = JSON.parse(JSON.stringify(this.listQuery));
        pamas.downloadContract = 1;
        purchaseOrderList(pamas).then((res)=>{
          let   data = res;
          let zip = new JSZip();
          let cache = {};
          let promises = [];
          data.forEach(item => {
            const promise = this.getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
              const arr_name = item.url.split("attname=");
              let file_name;
              if(item.extension != ''){
                file_name = arr_name[arr_name.length - 1] + '.' + item.extension; // 获取文件名
              }else{
                file_name = arr_name[arr_name.length - 1] ;
              }
              zip.file(file_name, data.data, {binary: true}); // 逐个添加文件
              cache[file_name] = data.data
            });
            promises.push(promise)
          });
          Promise.all(promises).then(() => {
            zip.generateAsync({type: "blob"}).then(content => { // 生成二进制流
              FileSaver.saveAs(content, "打包下载.zip") // 利用file-saver保存文件
              this.btnLoading2 = false;
            }).catch((rej)=>{
              console.log("rej",rej)
              this.$message({
                type: 'error',
                message: '下载失败'
              });
              this.btnLoading2 = false;
            })
          }).catch((eer)=>{
            console.log("err",err)
            this.$message({
              type: 'error',
              message: '下载失败'
            });
            this.btnLoading2 = false;
          })
        })

      },

      getFile(item){
        return new Promise((resolve, reject) => {
          axios({
            method:'get',
            url:item.url,
            responseType: 'arraybuffer'
          }).then(data => {
            resolve({data:data.data,extension:item.extension})
          }).catch(error => {
            reject(error.toString())
          })
        })
      },

      toAddPickUp(item){
        let routeData = this.$router.resolve({name:'addPickUp',query:{purchaseOrderSn:item.orderSn}});
        window.open(routeData.href);
      },
      //下载excle
      downloadExcel(){
        let data = JSON.parse(JSON.stringify(this.listQuery));
        data.isExport = 1;
        purchaseOrderList(data).then(res => {
          require.ensure([], () => {
            const { export_json_to_excel } = require('sheet/Export2Excel');
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          })
        })
      },

      //下载表格数据格式化
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
        //显示申请付款弹窗
        showDialog3(item){
          this.dialogVisible3 = true;
          supplierBalanceInfo({supplierId:item.supplierId}).then((res)=>{
            if(item.fromCompany.indexOf('普利成') != -1){
                this.appleForm.CashBalance = res.polisenCashBalance;
                this.appleForm.ChengduiBalance = res.polisenChengduiBalance;
            }else if(item.fromCompany.indexOf('塑盟') != -1){
              this.appleForm.CashBalance = res.sumengCashBalance;
              this.appleForm.ChengduiBalance = res.sumengChengduiBalance;
            }else if(item.fromCompany.indexOf('泛塑') != -1){
              this.appleForm.CashBalance = res.fansuCashBalance;
              this.appleForm.ChengduiBalance = res.fansuChengduiBalance;
            }
            this.appleForm.currentPrePayAmount = res.currentPrePayAmount
          });
          this.appleForm.orderId = item.orderId;
          this.appleForm.goodsRemark = item.goodsRemark;
          this.appleForm.applyPaymentCode = '';
          this.appleForm.applyPayTime = '';
          this.appleForm.applyPayAmount = '';
          this.appleForm.applyPayRemark = '';
          this.appleForm.orderAmount = item.orderAmount;
          this.appleForm.unPaidAmount = item.unPaidAmount;
          this.appleForm.hasPaidAmount = item.hasPaidAmount;
          this.appleForm.canApplyAmount = item.canApplyAmount;
          this.appleForm.contractUrl = item.contractUrl;
          this.appleForm.fromCompany = item.fromCompany;
          this.appleForm.supplierName = item.supplierName;
          this.appleForm.urgencyType = ''

        },
        //关闭申请付款弹窗
        handleClose3(){
            this.dialogVisible3 = false;
            this.$refs.appleForm.clearValidate();
        },

        //提交申请付款
        handleConfirm3(){
            this.$refs['appleForm'].validate((valid) => {
                if (valid) {
                  if(parseFloat(this.appleForm.applyPayAmount) > this.appleForm.currentPrePayAmount){ // 申请付款的金额超过了【目前预付款额度】
                    this.$confirm('当前付款申请中包含的预付款金额已经超过了目前预付款额度是否继续进行申请?', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(() => {
                        this.submitPay()
                    }).catch(() => {
                      this.$message({
                        type: 'info',
                        message: '已取消申请'
                      });
                    });
                  }else{
                   this.submitPay()
                  }
                }
            })
        },

      //提交付款申请
      submitPay(){
        if(this.appleForm.applyPaymentCode == 'chengdui' &&  this.appleForm.canApplyAmount <= 0){
          this.$message({
            message: '承兑支付时可申请金额小于等于0，不可以再次申请',
            type: 'error'
          });
          return false
        }
        this.btnLoading3 = true;
        let data = {};
        data.orderId = this.appleForm.orderId;
        data.applyPaymentCode = this.appleForm.applyPaymentCode;
        data.applyPayTime = this.appleForm.applyPayTime;
        data.applyPayAmount = this.appleForm.applyPayAmount;
        data.applyPayRemark = this.appleForm.applyPayRemark;
        data.urgencyType = this.appleForm.urgencyType;
        purchaseAddApplyPay(data).then(()=>{
          this.btnLoading3 = false;
          this.dialogVisible3 = false;
          this.getList()
        }).catch(()=>{
          this.btnLoading3 = false;
        })
      },

      //去详情页
      toInfo(item){
        let routeData = this.$router.resolve({name:'purchaseContractDetail',query:{id:item.orderId}});
        window.open(routeData.href);
      },
      //商品
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          this.loading = false;
          goodsList({keywords:query}).then((res)=>{
            this.options = res.list;
          })
        } else {
          this.options = [];
        }
      },

      //供应商
      getSupplierList() {
          supplierList().then((res)=>{
            this.options2 = res;
          })
      },

      //获取员工下拉选项
      getUserOptionList(){
        getOrderUsersList().then((res)=>{
          this.userOptionList = res;
        })
      },

      //选择员工名称
      handleSelectUserName(key,item){
        this.listQuery[key] = item.userId;
      },

      //客户名称输入匹配
      querySearch(queryString, cb){
        getCustomerOption({keywords:queryString}).then((res)=>{
          cb(res);
        })
      },

      //选择客户名称
      handleSelectCustomerName(item){
        this.listQuery.keywords = item.customerName
      },

      /**
       * 切换选择状态
       */
      handleSelect(key, keyPath){
        this.listQuery.tab = key;
        if(key != 'my' && key != 'all'){
          this.listQuery.orderState = null;
        }
        if(key == 'my' || key == 'all'){
          let now = new Date();
          let nowMonth = now.getMonth(); //当前月
          let nowYear = now.getFullYear(); //当前年
          //本月的开始时间
          let monthStartDate = new Date(nowYear, nowMonth, 1);
          //本月的结束时间
          let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
          let startDate = formatDate(monthStartDate, 'yyyy-MM-dd hh:mm:ss');
          let endDate = formatDate(monthEndDate, 'yyyy-MM-dd hh:mm:ss');
          this.listQuery.createDate = [startDate,endDate];
        }

        this.handleSearchList();
      },
      handleSizeChange(val){
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val){
        this.listQuery.pageNum = val;
        this.getList();
      },

      handleSearchList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },

      //获取订单列表
      getList() {
        this.listLoading = true;
        purchaseOrderList(this.listQuery).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.statisticsAmount = response.statisticsAmount;
          this.statisticsGoodsNum = response.statisticsGoodsNum;
          this.authNum = response.authNum;
          this.closeNum = response.closeNum;
          this.closeAmount = response.closeAmount
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
      },

    },
  }
</script>

<style scoped lang="scss">

</style>
